package com.web;

import com.pojo.Cart;
import com.pojo.User;
import com.service.OrderService;
import com.service.impl.OrderServiceImpl;
import com.utils.JdbcUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class OrderServlet extends BaseServlet{

        private OrderService orderService = new OrderServiceImpl();
    /**
     * 生成订单
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void createOrder(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 先获取 Cart 购物车对象
        Cart cart = (Cart) req.getSession().getAttribute("cart");
        // 获取 Userid
        User loginUser = (User) req.getSession().getAttribute("user");
        if (loginUser == null) {
            req.getRequestDispatcher("/pages/user/login.jsp").forward(req,resp);
            return;
        }

        System.out.println("OrderServlet程序在["+Thread.currentThread().getName()+"]线程中");

        Integer userId = loginUser.getId();
        // 调用 orderService.createOrder(Cart,Userid);生成订单
        String orderId = null;
        orderId = orderService.createOrder(cart, userId);
//        try {
//            orderId = orderService.createOrder(cart, userId);
//            JdbcUtils.commitAndClose();//如果没有异常，就直接提交
//        } catch (Exception e) {
//            JdbcUtils.rollbackAndClose();//如果有异常，就回滚事务
//            e.printStackTrace();
//        }
//        req.setAttribute("orderId", orderId);
        // 请求转发到/pages/cart/checkout.jsp //
//        req.getRequestDispatcher("/pages/cart/checkout.jsp").forward(req, resp);
        req.getSession().setAttribute("orderId",orderId);
        resp.sendRedirect(req.getContextPath()+"/pages/cart/checkout.jsp");
    }
}
